<template>
    <div class="announcement-bar" v-if="isVisible">
        <div class="announcement-content">
            <div class="scroll-container">
                <div class="scroll-text" :style="{ transform: `translateY(${scrollPosition}px)` }">
                    <!-- 第一组公告 -->
                    <div v-for="(item, index) in announcements" :key="index" class="announcement-item">
                        {{ item }}
                    </div>
                    <!-- 复制一组公告用于无缝衔接 -->
                    <div v-for="(item, index) in announcements" :key="'copy-'+index" class="announcement-item">
                        {{ item }}
                    </div>
                </div>
            </div>
        </div>
        <div class="close-button" @click="closeAnnouncement">
            <a-button type="text" shape="circle">
                <template #icon><CloseOutlined /></template>
            </a-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount ,getCurrentInstance} from 'vue';
import { CloseOutlined } from '@ant-design/icons-vue';
import { useCurrencyStore } from '@/store/currency'
const currencyStore = useCurrencyStore()
const { proxy } = getCurrentInstance()
// 公告内容
const announcements = [
    'Welcome to our website！',
    'New product launch, limited time special offer!',
    `Free Shipping on Orders Over ${currencyStore.currentCurrency.unit}${ proxy.$ConvertPrice(99) }`
];

// 控制公告栏显示状态
const isVisible = ref(true);

// 滚动位置
const scrollPosition = ref(0);
let scrollInterval: number;

// 关闭公告
const closeAnnouncement = () => {
    isVisible.value = false;
    // 触发自定义事件
    window.dispatchEvent(new CustomEvent('announcement-closed'));
};

// 开始滚动
const startScroll = () => {
    scrollInterval = window.setInterval(() => {
        scrollPosition.value -= 1;
        // 当滚动到第一组公告结束时，立即将位置调整到第二组开始处
        if (Math.abs(scrollPosition.value) >= announcements.length * 40) {
            scrollPosition.value = 0;
        }
    }, 50);
};

onMounted(() => {
    startScroll();
});

onBeforeUnmount(() => {
    if (scrollInterval) {
        clearInterval(scrollInterval);
    }
});
</script>

<style lang="scss" scoped>
.announcement-bar {
    position: relative;
    background-color: #fff;
    padding: 2px 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    border-top:1px solid #dddfdd;
    border-bottom:1px solid #dddfdd;
}

.announcement-content {
    flex: 1;
    text-align: center;
    overflow: hidden;
}

.scroll-container {
    height: 40px;
    overflow: hidden;
}

.scroll-text {
    transition: none; // 移除过渡效果，实现即时切换
}

.announcement-item {
    height: 40px;
    line-height: 40px;
    font-weight: 600;
    color: #333;
    font-size: 14px;
    //下划线
    text-decoration: underline;

}

.close-button {
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    z-index: 1;
}
</style>
